<template>
  <div class="supplier-management">
    <!-- 操作栏 -->
    <div class="operation-bar">
      <el-input
        v-model="searchText"
        placeholder="搜索供应商编号/名称/品类"
        style="width: 360px"
        clearable
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>新增供应商
      </el-button>
    </div>

    <!-- 数据表格 -->
    <el-table 
      :data="filteredSuppliers" 
      border 
      style="width: 100%"
      header-row-class-name="table-header"
      stripe
      highlight-current-row
    >
      <el-table-column prop="supplierId" label="供应商编号" width="200" sortable align="center" />
      <el-table-column prop="company" label="公司名称" width="200" align="center"/>
      <el-table-column prop="contact" label="联系人" width="200" align="center">
        <template #default="{ row }">
          <el-tag effect="plain" type="info">
            {{ row.contact }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="category" label="供应品类" width="200" align="center">
        <template #default="{ row }">
          <el-tag effect="plain" :type="categoryTagType[row.category]">
            {{ row.category }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="certification" label="认证状态" width="140" align="center">
        <template #default="{ row }">
          <el-tag :type="certTagType[row.certification]" effect="light">
            {{ certOptions.find(s => s.value === row.certification)?.label }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="license" label="营业执照号" width="260" align="center" />
      <el-table-column prop="coopDate" label="合作日期" width="200" sortable align="center"/>
      <el-table-column label="操作" width="192" fixed="right" align="center">
        <template #default="{ row }">
          <el-button size="small" type="primary" plain @click="handleEdit(row)">编辑</el-button>
          <el-button
            size="small"
            type="danger"
            plain
            @click="handleDelete(row.supplierId)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditMode ? '编辑供应商信息' : '新增供应商'"
      width="680"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        label-position="left"
      >
        <el-form-item label="供应商编号" prop="supplierId">
          <el-input 
            v-model="formData.supplierId" 
            :disabled="isEditMode"
            placeholder="SP开头+7位数字"
          />
        </el-form-item>
        <el-form-item label="公司名称" prop="company">
          <el-input v-model="formData.company" placeholder="请输入公司全称"/>
        </el-form-item>
        <el-form-item label="联系人" prop="contact">
          <el-input v-model="formData.contact" placeholder="负责人姓名及职务"/>
        </el-form-item>
        <el-form-item label="供应品类" prop="category">
          <el-select v-model="formData.category" placeholder="请选择品类">
            <el-option
              v-for="item in categories"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="认证状态" prop="certification">
          <el-select v-model="formData.certification" placeholder="请选择认证">
            <el-option
              v-for="item in certOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="营业执照号" prop="license">
          <el-input v-model="formData.license" placeholder="18位数字" />
        </el-form-item>
        <el-form-item label="合作日期" prop="coopDate">
          <el-date-picker
            v-model="formData.coopDate"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus } from '@element-plus/icons-vue'

// SessionStorage 操作工具
const STORAGE_KEY = 'supplier_management_state'
const saveToStorage = (state) => {
  sessionStorage.setItem(STORAGE_KEY, JSON.stringify(state))
}
const loadFromStorage = () => {
  const data = sessionStorage.getItem(STORAGE_KEY)
  return data? JSON.parse(data) : {}
}

// 品类配置
const categories = [
  '海鲜水产',
  '肉类禽蛋',
  '蔬菜水果',
  '粮油调味',
  '冷冻食品',
  '餐饮设备'
]

// 认证选项及样式
const certOptions = [
  { value: 'ISO', label: 'ISO认证' },
  { value: '有机', label: '有机认证' },
  { value: 'HACCP', label: 'HACCP认证' },
  { value: '无', label: '无认证' }
]

const certTagType = {
  'ISO':'success',
  '有机': 'warning',
  'HACCP': 'danger',
  '无': ''
}

// 品类标签样式映射
const categoryTagType = {
  '海鲜水产': 'info',
  '肉类禽蛋': 'danger',
  '蔬菜水果':'success',
  '粮油调味': 'warning',
  '冷冻食品': '',
  '餐饮设备': 'info'
}

// 初始化状态（优先从 SessionStorage 加载）
const storedState = loadFromStorage()

// 初始供应商数据（带存储恢复）
const suppliers = ref(storedState.suppliers || [
  {
    supplierId: 'SP2024001',
    company: '蓝海渔业有限公司',
    contact: '王海涛 经理',
    category: '海鲜水产',
    certification: 'HACCP',
    license: '91370200MA3F6B3K1C',
    coopDate: '2020-03-15'
  },
  {
    supplierId: 'SP2024002',
    company: '绿源有机农场',
    contact: '李芳 总监',
    category: '蔬菜水果',
    certification: '有机',
    license: '91370200MA3F4W8J8Y',
    coopDate: '2021-06-20'
  },
  {
    supplierId: 'SP2024003',
    company: '金谷粮油集团',
    contact: '张建国 副总',
    category: '粮油调味',
    certification: 'ISO',
    license: '91370200MA3F3R7J7X',
    coopDate: '2019-09-10'
  },
  {
    supplierId: 'SP2024004',
    company: '北极熊冷冻食品',
    contact: '陈莉莉 经理',
    category: '冷冻食品',
    certification: 'HACCP',
    license: '91370200MA3F2T6K6W',
    coopDate: '2022-08-01'
  },
  {
    supplierId: 'SP2024005',
    company: '鼎盛肉联厂',
    contact: '赵强 总监',
    category: '肉类禽蛋',
    certification: 'ISO',
    license: '91370200MA3F1Q5J5V',
    coopDate: '2018-04-12'
  },
  {
    supplierId: 'SP2024006',
    company: '厨神设备制造',
    contact: '孙婷婷 销售',
    category: '餐饮设备',
    certification: '无',
    license: '91370200MA3F0P4J4U',
    coopDate: '2023-11-05'
  },
  {
    supplierId: 'SP2024007',
    company: '鲜果时光',
    contact: '周敏 经理',
    category: '蔬菜水果',
    certification: '有机',
    license: '91370200MA3FZ94J3T',
    coopDate: '2022-02-28'
  },
  {
    supplierId: 'SP2024008',
    company: '海之味水产',
    contact: '吴浩 副总',
    category: '海鲜水产',
    certification: 'HACCP',
    license: '91370200MA3FY83J2S',
    coopDate: '2020-07-19'
  },
  {
    supplierId: 'SP2024009',
    company: '香满园调味品',
    contact: '郑伟 总监',
    category: '粮油调味',
    certification: 'ISO',
    license: '91370200MA3FX72J1R',
    coopDate: '2021-03-10'
  },
  {
    supplierId: 'SP2024010',
    company: '雪龙冷链物流',
    contact: '徐丽华 经理',
    category: '冷冻食品',
    certification: 'HACCP',
    license: '91370200MA3FW61J0Q',
    coopDate: '2019-09-22'
  }
])

// 搜索功能（带存储恢复）
const searchText = ref(storedState.searchText || '')
const filteredSuppliers = computed(() => {
  return suppliers.value.filter(supplier => {
    return Object.values(supplier).some(value => 
      String(value).toLowerCase().includes(searchText.value.toLowerCase())
    )
  })
})

// 对话框相关状态（带存储恢复）
const dialogVisible = ref(storedState.dialogVisible || false)
const isEditMode = ref(storedState.isEditMode || false)
const formRef = ref(null)
const formData = reactive(storedState.formData || {
  supplierId: '',
  company: '',
  contact: '',
  category: '',
  certification: '无',
  license: '',
  coopDate: new Date().toISOString().split('T')[0]
})

// 表单验证规则
const formRules = {
  supplierId: [
    { required: true, message: '请输入供应商编号', trigger: 'blur' },
    { pattern: /^SP\d{7}$/, message: '格式要求：SP+7位数字', trigger: 'blur' }
  ],
  company: [{ required: true, message: '请输入公司名称', trigger: 'blur' }],
  category: [{ required: true, message: '请选择供应品类', trigger: 'change' }],
  license: [
    { required: true, message: '请输入营业执照号', trigger: 'blur' },
    { pattern: /^[A-Z0-9]{18}$/, message: '请输入有效营业执照号', trigger: 'blur' }
  ],
  coopDate: [{ required: true, message: '请选择合作日期', trigger: 'change' }]
}

// 状态变化时自动保存到 SessionStorage
watch([suppliers, searchText, dialogVisible, isEditMode, () => ({ ...formData })], () => {
  saveToStorage({
    suppliers: suppliers.value,
    searchText: searchText.value,
    dialogVisible: dialogVisible.value,
    isEditMode: isEditMode.value,
    formData: { ...formData }
  })
}, { deep: true })

// 操作函数
const handleAdd = () => {
  isEditMode.value = false
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  isEditMode.value = true
  Object.assign(formData, { ...row })
  dialogVisible.value = true
}

const handleDelete = (supplierId) => {
  ElMessageBox.confirm('确定要删除该供应商吗？', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    suppliers.value = suppliers.value.filter(u => u.supplierId!== supplierId)
    ElMessage.success('删除成功')
  })
}

const submitForm = async () => {
  await formRef.value.validate()
  if (isEditMode.value) {
    const index = suppliers.value.findIndex(u => u.supplierId === formData.supplierId)
    suppliers.value.splice(index, 1, { ...formData })
  } else {
    if (suppliers.value.some(u => u.supplierId === formData.supplierId)) {
      return ElMessage.warning('供应商编号已存在')
    }
    suppliers.value.push({ ...formData })
  }
  dialogVisible.value = false
  ElMessage.success(isEditMode.value? '修改成功' : '新增成功')
}

const resetForm = () => {
  formData.supplierId = ''
  formData.company = ''
  formData.contact = ''
  formData.category = ''
  formData.certification = '无'
  formData.license = ''
  formData.coopDate = new Date().toISOString().split('T')[0]
}

// 初始化时恢复弹窗状态（可选，确保表单数据正确）
onMounted(() => {
  const dialogState = loadFromStorage().dialogState || {}
  dialogVisible.value = dialogState.dialogVisible || false
  isEditMode.value = dialogState.isEditMode || false
  Object.assign(formData, dialogState.formData || {})
})
</script>

<style scoped lang="scss">
.supplier-management {
  padding: 24px;
  background: #f8fafc;
  min-height: 100vh;

  .operation-bar {
    padding: 16px 24px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(44, 62, 80, 0.08);
    margin-bottom: 24px;
    display: flex;
    align-items: center;
    gap: 16px;
  }

  :deep(.table-header) th {
    background-color: #f8fafc !important;
    color: #64748b;
    font-weight: 600;
    height: 56px;
  }

  .el-table {
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(44, 62, 80, 0.08);
    
    .el-tag {
      font-size: 13px; 
      // 可根据需求继续扩展样式，如颜色、内边距等
      // color: #333;
      // padding: 2px 6px;
    }
  }
}
</style>